`
https://leetcode.cn/problems/closest-equal-element-queries/
`

/**
 * @param {number[]} nums
 * @param {number[]} queries
 * @return {number[]}
 */
var solveQueries = function (nums, queries) {
  // 存储出现位置的索引，必然递增，方便二分
  const idxss = nums.reduce((acc, cur, idx) => {
    if (!acc.has(cur)) acc.set(cur, [])
    const target = acc.get(cur)
    target.push(idx)
    return acc
  }, new Map())
  // 添加哨兵下标来模拟循环数组
  const n = nums.length
  for (const [_, idxs] of idxss) {
    // 只有自己一个数字就没必要加哨兵了
    if (idxs.length === 1) continue
    const first = idxs[0], last = idxs.at(-1)
    idxs.unshift(last - n)
    idxs.push(first + n)
  }
  return queries.map((query) => {
    // 找到对应的索引集
    const target = idxss.get(nums[query])
    if (target.length === 1) return -1
    // 找到 query 找到 target
    const index = _.sortedIndex(target, query)
    return Math.min(
      Math.abs(query - target[index - 1]),
      Math.abs(query - target[index + 1])
    )
  })
};